<?php

namespace Modules\Task\Providers;

use Cron\CronExpression;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Modules\Task\Console\Commands\ListSchedule;
use Modules\Task\Console\Commands\PublishAssets;
use Modules\Task\Console\DemoCommand;
use Modules\Task\Contracts\TaskInterface;
use Modules\Task\Repositories\EloquentTaskRepository;
use Modules\Task\Models\Totem;

class TaskServiceProvider extends ServiceProvider
{
    /**
     * @var string $moduleName
     */
    protected $moduleName = 'Task';

    /**
     * @var string $moduleNameLower
     */
    protected $moduleNameLower = 'task';


    /**
     * Bootstrap any services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerResources();

        Validator::extend('cron_expression', function ($attribute, $value, $parameters, $validator) {
            return CronExpression::isValidExpression($value);
        });

        Validator::extend('json_file', function ($attribute, UploadedFile $value, $validator) {
            return $value->getClientOriginalExtension() == 'json';
        });
    }

    /**
     * Register any services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(ConsoleServiceProvider::class);

        $this->mergeConfigFrom(
            __DIR__.'/../Config/config.php',
            'task'
        );

        if (! defined('TOTEM_PATH')) {
            define('TOTEM_PATH', realpath(__DIR__.'/../'));
        }

        if (! defined('TOTEM_TABLE_PREFIX')) {
            define('TOTEM_TABLE_PREFIX', config('task.table_prefix'));
        }

//        if (! defined('TOTEM_DATABASE_CONNECTION')) {
//            define('TOTEM_DATABASE_CONNECTION', config('task.database_connection', Schema::getConnection()->getName()));
//        }

        $this->commands([
            ListSchedule::class,
            DemoCommand::class
        ]);

        $this->app->bindIf('task.tasks', EloquentTaskRepository::class, true);
        $this->app->alias('task.tasks', TaskInterface::class);
        $this->app->register(TotemRouteServiceProvider::class);
        $this->app->register(TotemEventServiceProvider::class);
    }

    /**
     * Register the Totem resources.
     *
     * @return void
     */
    protected function registerResources()
    {
        $this->loadViewsFrom(__DIR__.'/../Resources/views', 'task');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        $this->loadTranslationsFrom(__DIR__.'/../Resources/lang', 'task');
    }

}
